/*
 * Copyright 2011 Philippe Blanc.
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
package me.l1k3.ui.client;

import me.l1k3.fx.client.FXFade;
import me.l1k3.fx.client.inter.FXShowAndHide;
import me.l1k3.ui.client.css.BlockerResources;
import me.l1k3.ui.client.inter.Blocker;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.FlowPanel;

public class BlockerPanel extends FlowPanel implements Blocker {
	private Element blocker;
    private FXShowAndHide effect;
	private double alpha;
	private int time;
	
	public BlockerPanel() {
		this(300, 0.5);
	}
	
	public BlockerPanel(int time, double alpha) {
	    BlockerResources.INSTANCE.css().ensureInjected();
	    
	    this.time = time;
		this.alpha = alpha;
		
		blocker = DOM.createDiv();
        blocker.setClassName("blocker");
        getElement().appendChild(blocker);
        
        if(isAttached()) {
            lazyInitialization();
        }
	}
	
    @Override
    protected void onLoad() {
        super.onLoad();
        lazyInitialization();
    }
	
	public void addClassToBlocker(String className) {
	    getBlocker().addClassName(className);
	}
	
	public void removeClassToBlocker(String className) {
        getBlocker().removeClassName(className);
    }
	
	protected Element getBlocker() {
	    return blocker;
	}
	
	public void block() {
	    block(null);
	}
	
	public void block(Command callback) {
		if(effect!=null) {
		    if(callback!=null)
		        effect.show(time).callback(callback);
		    else
		        effect.show(time);
		} else if (callback != null) {
            Scheduler.get().scheduleDeferred(callback);
        }
	}

	public void release() {
	    release(null);
	}
	
	public void release(Command callback) {
		if(effect!=null) {
		    if(callback!=null)
	            effect.hide(time).callback(callback);
	        else
	            effect.hide(time);
		} else if (callback != null) {
            Scheduler.get().scheduleDeferred(callback);
        }
	}
	
    private void lazyInitialization() {
        effect = FXFade.smartRange(getBlocker(), alpha, 0).hide();
    }
}
